package double_pointer;

public class DuplicateZeros {
    //复写 0
    public void duplicateZeros(int[] arr) {
        int cur = 0;
        int dest = -1;
        int n = arr.length;
        //1. 找到最后一个需要复写的数
        while (cur < n) {
            if (arr[cur] != 0) {
                dest++;
            } else {
                dest += 2;
            }
            if(dest >= n - 1) {
                break;
            }
            cur++;
        }
        //2. 处理一下边界情况
        if(dest == n) {
            arr[n - 1] = 0;
            cur--;
            dest -= 2;
        }
        //3. 从后向前完成复写操作
        while(cur >= 0) {
            if(arr[cur] != 0) {
                arr[dest] = arr[cur];
                dest--;
                cur--;
            } else {
                arr[dest--] = 0;
                arr[dest--] = 0;
                cur--;
            }
        }
    }
}
